package com.web.controller;

import com.domain.Employee;
import com.github.pagehelper.PageInfo;
import com.qo.EmployeeQueryObject;
import com.service.DepartmentService;
import com.service.EmployeeService;
import com.service.RoleService;
import com.util.JsonResult;
import com.util.UserContext;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author shkstart
 * @create 2022/3/11-11:46
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService service;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private RoleService roleService;

    //查询员工
    @RequiresPermissions(value = {"employee:list","员工列表"},logical = Logical.OR)
    @RequestMapping("/list")   //可以访问 8080/employee/list.do 默认自动添加.do
    public String list(Model model, EmployeeQueryObject queryObject){
        //分页查询数据
        PageInfo<Employee> result = service.query(queryObject);
        model.addAttribute("result",result);

        //部门下拉框数据，查询所有部门存入域中，让页面获取到
        model.addAttribute("depts", departmentService.listAll());

        //将queryObject存入域中，为了让表单回显输入框
        model.addAttribute("qo", queryObject);

        // 跳转页面 /WEB-INF/views/employee/list.ftl
        return "employee/list";
    }

    //删除员工
    @RequiresPermissions(value = {"employee:delete","员工删除"},logical = Logical.OR)
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            if (id != null){  //传id值就删除对应的数据
                service.delete(id);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }
    }

    //添加、编辑
    //从前端页面可知，如携带id，则是编辑；若没有id，则是添加
    @RequiresPermissions(value = {"employee:input","员工编辑"},logical = Logical.OR)
    @RequestMapping("/input")
    public String input(Long id,Model model){
        //部门下拉框数据，查询所有部门存入域中，让页面获取到
        model.addAttribute("depts", departmentService.listAll());
        //查询所有角色存入域中，让页面获取到
        model.addAttribute("roles", roleService.listAll());

        if (id != null) {  //是编辑，需要查询被修改的员工，回显在页面上
            model.addAttribute("entity",service.get(id));
        }
        // 跳转页面 /WEB-INF/views/employee/input.ftl
        return "employee/input";
    }

    //修改、保存员工
    @RequiresPermissions(value = {"employee:saveOrUpdate","员工保存或更新"},logical = Logical.OR)
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee, Long[] ids){
        if (employee.getId() != null) {  //是编辑
            service.update(employee,ids);
        }else{   //是添加
            service.save(employee,ids);
        }
        return new JsonResult();
    }

    @RequestMapping("/update")
    public String update(){
        // 跳转页面 /WEB-INF/views/employee/list.ftl
        return "pwd/updatePwd";
    }
    //修改密码操作
    @RequestMapping("/updatePwd")
    @ResponseBody
    public JsonResult updatePwd(String oldPassword, String newPassword){
        //获取当前登录用户信息
        Employee currentUser = UserContext.getCurrentUser();
        //判空
        if (!StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)){
            return new JsonResult(false, "未输入数据");
        }
        //判断原密码是否正确
        if (!oldPassword.equals(currentUser.getPassword())){
            return new JsonResult(false, "原密码错误");
        }
        //更新新密码
        currentUser.setPassword(newPassword);
        service.updatePassword(currentUser);
        return new JsonResult();
    }

    @RequestMapping("/rest")
    public String rest(Long id,Model model){
        //页面显示要被重置密码的员工姓名
        if (id == null) {
            throw new RuntimeException("员工没有 id");
        }
        model.addAttribute("entity",service.get(id));
        // 跳转页面 /WEB-INF/views/employee/list.ftl
        return "pwd/resetPwd";
    }
    //重置密码操作
    @RequestMapping("/resetPwd")
    @ResponseBody
    public JsonResult resetPwd(Employee employee,String newPassword){
        //获取当前登录用户信息
        if (!UserContext.getCurrentUser().isAdmin()){
            return new JsonResult(false, "您没有权限操作");
        }
        //判空
        if ( !StringUtils.hasText(newPassword)){
            return new JsonResult(false, "未输入数据");
        }
        //更新新密码
        employee.setPassword(newPassword);
        service.updatePassword(employee);
        return new JsonResult();
    }

    //账号恢复、禁用操作
    @RequestMapping("/changeStatus")
    @ResponseBody
    public JsonResult changeStatus(Long id){
        //获取当前登录用户信息
        if (!UserContext.getCurrentUser().isAdmin()){
            return new JsonResult(false, "您没有权限操作");
        }
        //获取当前点击的用户信息
        Employee employee = service.get(id);
        //判断此用户的状态
        if (employee.isStatus()){
            employee.setStatus(false);
            service.updateStatus(employee);
            return new JsonResult();
        }
        employee.setStatus(true);
        service.updateStatus(employee);
        return new JsonResult();
    }

    //批量删除
    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(Long[] ids){
        service.batchDelete(ids);
        return new JsonResult();
    }

    //验证用户名是否存在
    /*@RequestMapping("/checkName")
    @ResponseBody
    public HashMap checkName(String name){    // valid:true
        //valid 的key是插件规定的，不能更改；true表示验证通过、false表示不通过，已存在
        Employee employee = service.selectByName(name);
        HashMap<String, Boolean> map = new HashMap<>();
        map.put("valid",employee==null);
        return map;
    }*/
    @RequestMapping("/checkName")
    @ResponseBody
    public HashMap checkName(Long id, String name){    // valid:true
        HashMap<String, Boolean> map = new HashMap<>();
        if (id != null) {  //是编辑
            Employee empbyid = service.get(id);
            //判断用户名是否被更改
            if (empbyid.getName().equals(name)){  //未被更改
                map.put("valid",true);
            }else {  //用户名被更改，需要验证
                Employee empbyname = service.selectByName(name);
                map.put("valid",empbyname==null);
            }
            return map;
        }else{   //是添加
            Employee employee = service.selectByName(name);
            map.put("valid",employee==null);
            return map;
        }
    }

    //导出
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //创建excel文件
        Workbook wb = service.exportXls();
        //把excel的数据输出给浏览器
        wb.write(response.getOutputStream());
    }

    //导入
    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws Exception {
        service.importXls(file);
        return new JsonResult();
    }
}
